Convert Octal Number to Decimal and vice-versa using C++

04-11-17 Course- CPP

This program converts either octal number entered by user to decimal number or decimal number entered by user to octal in accordance with the character entered by user.

Source Code to Convert Octal Number to Decimal and Vice Versa


/* C++ programming source code to convert either octal to decimal or decimal to octal according to data entered by user. */

#include <iostream>
#include <cmath>
using namespace std;
int decimal_octal(int n);
int octal_decimal(int n);
int main()
{
   int n;
   char c;
   cout << "Instructions: " << endl;
   cout << "1. Enter alphabet 'o' to convert decimal to octal." << endl;
   cout << "2. Enter alphabet 'd' to convert octal to decimal." << endl;
   cin >> c;
   if (c =='d' || c == 'D')
   {
       cout << "Enter a octal number: ";
       cin >> n;
       cout << n << " in octal = " << octal_decimal(n) << " in decimal";
   }
   if (c =='o' || c == 'O')
   {
       cout << "Enter a decimal number: ";
       cin >> n;
       cout << n << " in decimal = " << decimal_octal(n) << " in octal";
   }
   return 0;
}

int decimal_octal(int n) /* Function to convert decimal to octal */
{
    int rem, i=1, octal=0;
    while (n!=0)
    {
        rem=n%8;
        n/=8;
        octal+=rem*i;
        i*=10;
    }
    return octal;
}

int octal_decimal(int n) /* Function to convert octal to decimal */
{
    int decimal=0, i=0, rem;
    while (n!=0)
    {
        rem = n%10;
        n/=10;
        decimal += rem*pow(8,i);
        ++i;
    }
    return decimal;
}

Output


Instructions:
1. Enter alphabet 'o' to convert decimal to octal.
2.  Enter alphabet 'd' to convert octal to decimal.
d
Enter an octal number: 2341
2341 in octal = 1249 in decimal

This program asks user to enter a character and in accordance with that character user is asked to enter either octal number or decimal number. If user chooses to convert octal number to decimal then, that number is passed to function octal_decimal(). This function will convert the octal number passed by user to decimal number and returns it to main function. Similarly, if user chooses to convert decimal number to octal then, that number is passed to function decimal_octal(). This function will convert decimal number to octal number and returns it to main function.